package com.imooc.pan.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imooc.pan.config.AlipayConfig;
import com.imooc.pan.entity.PayRecord;
import com.imooc.pan.entity.StorageOrder;
import com.imooc.pan.service.PayRecordService;
import com.imooc.pan.service.StorageOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

/**
 * @author Mr.M
 * @version 1.0
 * @description 订单相关的接口
 * @date 2023/2/26 10:09
 */
@Api(value = "订单支付接口", tags = "订单支付接口")
@Slf4j
@Controller
public class OrderController {

    @Autowired
    StorageOrderService storageOrderService;

    @Autowired
    private PayRecordService payRecordService;
    
  /*  @Value("${pay.alipay.APP_ID}")
    String APP_ID;
    @Value("${pay.alipay.APP_PRIVATE_KEY}")
    String APP_PRIVATE_KEY;

    @Value("${pay.alipay.ALIPAY_PUBLIC_KEY}")
    String ALIPAY_PUBLIC_KEY;*/
    
    // String APP_ID = "2021000122675149";
    // @Value("${pay.alipay.APP_PRIVATE_KEY}")
    // String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCr/XnqLUV8ayE/9WoT1UYq/zXYvk85Lmx8kn/TR6c6r6AS58by+XGh+tlmsVCm2kSo2BVO/c67dX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VfRusTuneol92l16MNVW3ylxf1/Pzo+xLgWMFbIwUY9itL39X6mXbeaHNIMRAoGBAKdPPIo2ci2F3kQWgL4t4gZQT1ZmAVuu6FEIPTxOLyAsXlT3J5N43l/52tP7dDy+y3d+sciGFDJVN7kRrbHPZiZZIDqM6LVgMM2jezIJURZyLrmEMg8IRGnSKapjaMeFDNISIvkX3v01ELeidsgAzrBIRgdCimftqQihwyxu1BlZAoGBAMLJ6fDj7rZKbTLMih40KXB+1O6c3PC1MAAwAVACEBhQsU4/wqF9KjuT/xk4lknh3xOO/eZmObIM+yynrHEG62YZC7Zhjv9zges+KSd+eKOuAMKaW86RAP52JlVYJpq06MukI65308A2Z/z0J+/r1HEmfXqfQvTxx7dVbQGznpnc";
    
    // @Value("${pay.alipay.ALIPAY_PUBLIC_KEY}")
    // String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqQcGRKQUoU3NliJvrfQQstqRBQV7+C5zJPp/OlWpm4atyVcz4LRO0ZFRVsLUcNkEydMz49iSfscWi0Lp3R8CsMUELZ8lwLtmVMsogz3v6yXyxgdSilZ+qOZOmiEoIzrIKIM1iILidq2Ad9m8grgAYK3+gnfu16dpEY7zsefGITUL6eE/vSRtDzLBMEw4SAHcD9Yczr3dnD5ZzyIOuG5S2FVYtp2/qGCNez98CF2ZYun8KZmns03AejwJLRUq+F18i+Hcsct7Qla215d6D70goWqU/CNlZUSPCzvQAABw83kJbjY9mDqib9r5aT8ANP0ONMxXA6NkGnarPoJqyhgDrwIDAQAB";
    
    
    /*@ApiOperation("生成支付二维码")
    @PostMapping("/generatepaycode")
    @ResponseBody
    public R generatePayCode(@RequestBody AddOrderDto addOrderDto, HttpServletResponse httpResponse) {

        *//*SecurityUtil.XcUser user = SecurityUtil.getUser();
        String userId = user.getId();*//*

        //调用service，完成插入订单信息、插入支付记录、生成支付二维码
        *//*PayRecordDto payRecordDto = orderService.createOrder(userId, addOrderDto);*//*
        // RestResponse response = null;
        // try {
        //     response = requestpay(String.valueOf(payRecordDto.getPayNo()), httpResponse);
        // } catch (Exception e) {
        //     log.error("获取支付二维码失败");
        //     throw new RuntimeException("获取支付二维码失败,请联系管理员");
        // }
        *//*return payRecordDto;*//*
        // return response;
    }*/

    @ApiOperation("扫码下单接口")
    @RequestMapping("/requestpay")
    // @LoginIgnore
    public void requestpay(String payNo, HttpServletResponse httpResponse) throws IOException, AlipayApiException {
        // 通过订单号 进行支付
        LambdaQueryWrapper<StorageOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorageOrder::getPayNo, payNo);
        StorageOrder storageOrder = storageOrderService.getOne(queryWrapper);
        if (Objects.isNull(storageOrder)){
            log.error("支付记录不存在，订单号：{}",payNo);
            throw new RuntimeException("支付记录不存在");
        }
        if ("1" == storageOrder.getStatus()){
            throw new RuntimeException("当前订单已完成支付，请勿重复支付");
        }
        
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, AlipayConfig.FORMAT,
                                                            AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // String notifyUrl = AlipayConfig.NOTIFY_URL + "payResult=true&payNo=" + payNo;
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
        // 支付成功后，跳转到当前页面
        request.setReturnUrl("http://localhost:5173/paycallback?payNo="+payNo);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", payNo);
        bizContent.put("total_amount", storageOrder.getTotalPrice());
        bizContent.put("subject", storageOrder.getOrderName());
        // 电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        // 销售产品码，与支付宝签约的产品码名称。目前电脑支付场景下仅支持 FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //2：订单码-跳转模式 二维码模型 https://opendocs.alipay.com/open/59da99d0_alipay.trade.page.pay
        bizContent.put("qr_pay_mode", 2);
    
        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);
    
        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);
    
        //// 结算信息，按需传入
        //JSONObject settleInfo = new JSONObject();
        //JSONArray settleDetailInfos = new JSONArray();
        //JSONObject settleDetail = new JSONObject();
        //settleDetail.put("trans_in_type", "defaultSettle");
        //settleDetail.put("amount", 0.01);
        //settleDetailInfos.add(settleDetail);
        //settleInfo.put("settle_detail_infos", settleDetailInfos);
        //bizContent.put("settle_info", settleInfo);
    
        //// 二级商户信息，按需传入
        //JSONObject subMerchant = new JSONObject();
        //subMerchant.put("merchant_id", "2088000603999128");
        //bizContent.put("sub_merchant", subMerchant);
    
        //// 业务参数信息，按需传入
        //JSONObject businessParams = new JSONObject();
        //businessParams.put("busi_params_key", "busiParamsValue");
        //bizContent.put("business_params", businessParams);
    
        //// 营销信息，按需传入
        //JSONObject promoParams = new JSONObject();
        //promoParams.put("promo_params_key", "promoParamsValue");
        //bizContent.put("promo_params", promoParams);
    
        request.setBizContent(bizContent.toString());
        // AlipayTradePrecreateResponse response = alipayClient.execute(request);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        String form = response.getBody();
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        
        /*AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, APP_ID, APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
//        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
        alipayRequest.setNotifyUrl("http://6zyw75.natappfree.cc/api/orders/paynotify");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+payNo+"\"," +
                "    \"total_amount\":"+payRecordByPayno.getTotalPrice()+"," +
                "    \"subject\":\""+payRecordByPayno.getOrderName()+"\"," +
                "    \"product_code\":\"QUICK_WAP_WAY\"" +
                "  }");//填充业务参数
        String form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK请求支付宝下单
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();*/


    }
    
    
    //接收支付宝通知
    @PostMapping("/paynotify")
    // @LoginIgnore
    public void paynotify(HttpServletRequest request,
                          HttpServletResponse response) throws IOException,
            AlipayApiException {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY,
                                                           AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);

        if(verify_result){//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            // 获取支付时间
            String gmt_payment = new String(request.getParameter("gmt_payment").getBytes("ISO-8859-1"),"UTF-8");
            //
            String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");
            if (trade_status.equals("TRADE_SUCCESS")){
                //更新支付记录表的支付状态为成功，订单表的状态为成功
                PayRecord payRecord = new PayRecord();
                payRecord.setPayNo(out_trade_no);
                // 支付宝
                payRecord.setTradeNo(trade_no);
                payRecord.setTotalPrice(total_amount);
                payRecord.setStatus(trade_status);
                payRecord.setAppId(AlipayConfig.APP_ID);
                payRecord.setPaySuccessTime(DateUtil.parse(gmt_payment, "yyyy-MM-dd HH:mm:ss"));
                payRecord.setOrderName(subject);
                payRecordService.saveRecond(payRecord);
            }
            response.getWriter().write("success");
        }else{//验证失败
            response.getWriter().write("failure");
        }
    }
    
/*    @GetMapping("/paynotify")
    @LoginIgnore
    public void test(@RequestParam("payNo") String payNo, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        
       
            String url = "http://localhost:5173/paycallback?payResult=true&payNo=" + payNo;
            // response.getWriter().write("fail");
            response.sendRedirect(url);
        }*/
    
}
